import {
    getCurrentUserPagePermissionsApi,
    getCurrentUserPagePermissionsFail,
    getCurrentUserPagePermissionsSuccess
} from 'Shared/actions/currentUserContext';
import {PAGE_CODE} from './constants';
import {getPathById, getObjById} from './utils';
import * as api from './api';
import {workItemCategoryStatus} from '../Enum';
/*==============================初始化API================================= */
export const GET_INIT_BEGIN = 'GET_INIT_BEGIN';
export const GET_INIT_SUCCESS = 'GET_INIT_SUCCESS';
export const GET_INIT_FAIL = 'GET_INIT_FAIL';
export const getInitDataBegin = () => ({
    type: GET_INIT_BEGIN
});
export const getInitDataSuccess = data => ({
    type: GET_INIT_SUCCESS,
    data,
});
export const getInitDataFail = () => ({
    type: GET_INIT_FAIL,
});
/*==============================初始化车型================================= */
export const GET_INIT_CATEGORY_DATA_BEGIN = 'GET_INIT_CATEGORY_DATA_BEGIN';
export const GET_INIT_CATEGORY_DATA_SUCCESS = 'GET_INIT_CATEGORY_DATA_SUCCESS';
export const GET_INIT_CATEGORY_DATA_FAIL = 'GET_INIT_CATEGORY_DATA_FAIL';
const getInitCategoryDataBegin = () => ({
    type: GET_INIT_CATEGORY_DATA_BEGIN
});

const getInitCategoryDataSuccess = data => ({
    type: GET_INIT_CATEGORY_DATA_SUCCESS,
    data
});
const getInitCategoryDataFail = () => ({
    type: GET_INIT_CATEGORY_DATA_FAIL
});
export const getInitData = (code = PAGE_CODE) => dispatch => {
    dispatch(getInitDataBegin());
    const init = api.initQuery().then(res => {
        if(res.ok)
            dispatch(getInitDataSuccess(res.data));
        else
            dispatch(getInitDataFail());
        return res.ok;
    });
    dispatch(getInitCategoryDataBegin());
    const category = api.productCategoryQuery().then(res => {
        if(res.ok)
            dispatch(getInitCategoryDataSuccess(res.data));
        else
            dispatch(getInitCategoryDataFail());
        return res.ok;
    });
    const permissions = getCurrentUserPagePermissionsApi(code).then(res => {
        if(res.isOk) dispatch(getCurrentUserPagePermissionsSuccess(res.data));
        else dispatch(getCurrentUserPagePermissionsFail(res.statusCode, res.message));
        return res.isOk;
    });
    return Promise.all([init, permissions, category]).then(values => values[0] && values[1] && values[2]);
};

export const GET_CATEGORY_BEGIN = 'GET_CATEGORY_BEGIN';
export const GET_CATEGORY_SUCCESS = 'GET_CATEGORY_SUCCESS';
export const GET_CATEGORY_FAIL = 'GET_CATEGORY_FAIL';
export const getCategoryBegin = () => ({
    type: GET_CATEGORY_BEGIN
});

export const getCategorySuccess = (data, parentId) => (dispatch, getState) => {
    const trees = getState().getIn(['page', 'domainData', 'categories', 'data']).toJS();
    const path = getPathById(trees, parentId) || [];
    const newData = parentId ? data.map(item => {
        item.parentId = parentId;
        return item;
    }) : data;
    return dispatch({
        type: GET_CATEGORY_SUCCESS,
        data: newData,
        path
    });
};
export const getCategoryFail = () => ({
    type: GET_CATEGORY_FAIL,
});
export const getTopCategories = (forceRefresh = true) => (dispatch, getState) => {
    if(!forceRefresh) {
        const categories = getState().getIn(['page', 'domainData', 'categories', 'data']);
        if(categories && !categories.isEmpty())
            return Promise.resolve(true);
    }
    dispatch(getCategoryBegin());
    return api.getCategoriesTop().then(res => {
        if(res.ok) {
            const {content = []} = res.data;
            const data = content.map(item => ({
                items: [],
                ...item
            }));
            dispatch(getCategorySuccess(data || []));
        } else
            dispatch(getCategoryFail());
        return res.ok;
    });
};

export const getCategoryChildren = parentId => dispatch =>
    // dispatch(getCategoryBegin());
    api.getCategories(parentId).then(res => {
        if(res.ok) {
            const {content = []} = res.data;
            const data = content.map(item => ({
                items: [],
                ...item
            }));
            dispatch(getCategorySuccess(data, parentId));
        } else
            dispatch(getCategoryFail());
        return res.ok;
    })
;
/*==============================查询列表================================= */

export const GET_WORKITEMS_BEGIN = 'GET_WORKITEMS_BEGIN';
export const GET_WORKITEMS_SUCCESS = 'GET_WORKITEMS_SUCCESS';
export const GET_WORKITEMS_FAIL = 'GET_WORKITEMS_FAIL';
export const getWorkItemsBegin = () => ({
    type: GET_WORKITEMS_BEGIN
});
export const getWorkItemsSuccess = (data, condition) => ({
    type: GET_WORKITEMS_SUCCESS,
    data,
    condition
});
export const getWorkItemsFail = () => ({
    type: GET_WORKITEMS_FAIL,
}); //获取列表

export const getWorkItems = condition => dispatch => {
    // eslint-disable-next-line no-unneeded-ternary
    condition.isCustomed = condition.isCustomed === 1 ? true : false;
    dispatch(getWorkItemsBegin());
    return api.getWorkItems(condition).then(res => {
        if(res.ok)
            dispatch(getWorkItemsSuccess(res.data, condition));
        else
            dispatch(getWorkItemsFail());
        return res.ok;
    });
}; //按钮搜索


export const querySearch = () => (dispatch, getState) => {
    const condition = getState()
        .getIn(['page', 'appState', 'queryCondition'])
        .toJS();
    dispatch(getWorkItems((condition)));
}; //分页排序搜索

export const tableSearch = page => (dispatch, getState) => {
    const query = getState()
        .getIn(['page', 'appState', 'queryBySort'])
        .toJS();
    const condition = Object.assign({}, query, page);
    dispatch(getWorkItems(condition));
};


export const categorySearch = id => (dispatch, getState) => {
    const condition = getState().getIn(['page', 'appState', 'queryBySort']).toJS();
    condition.workItemCategoryId = id;
    return dispatch(getWorkItems(condition));
};

/*==============================导出================================= */
export const exportData = () => (dispatch, getState) => {
    const {pageIndex, pageSize, isCustomed, ...props} = getState()
        .getIn(['page', 'appState', 'queryCondition'])
        .toJS() || {};
    return api.exportWorkItem({
        ...props,
        // eslint-disable-next-line no-unneeded-ternary
        isCustomed: isCustomed === 1 ? true : false
    });
};

/*==============================高级查询================================= */

export const GET_WPC_BEGIN = 'GET_WPC_BEGIN';
export const GET_WPC_SUCCESS = 'GET_WPC_SUCCESS';
export const GET_WPC_FAIL = 'GET_WPC_FAIL';
export const getWPCBegin = () => ({
    type: GET_WPC_BEGIN
});
export const getWPCSuccess = (data, condition) => ({
    type: GET_WPC_SUCCESS,
    data,
    condition
});
export const getWPCFail = () => ({
    type: GET_WPC_FAIL,
}); //获取列表

export const getWPCs = condition => dispatch => {
    dispatch(getWPCBegin());
    return api.getWPC(condition).then(res => {
        if(res.ok)
            dispatch(getWPCSuccess(res.data, condition));
        else
            dispatch(getWPCFail());
        return res.ok;
    });
}; //按钮搜索

export const queryHighSearch = () => (dispatch, getState) => {
    const condition = getState()
        .getIn(['page', 'appState', 'queryHighCondition'])
        .toJS();
    const {productCategoryName, ...props} = condition;
    dispatch(getWPCs(props));
}; //分页排序搜索

export const tableHighSearch = page => (dispatch, getState) => {
    const query = getState()
        .getIn(['page', 'appState', 'queryHighBySort'])
        .toJS();
    const condition = Object.assign({}, query, page);
    dispatch(getWPCs(condition));
};


export const categoryHighSearch = id => (dispatch, getState) => {
    const condition = getState().getIn(['page', 'appState', 'queryHighBySort']).toJS();
    condition.workItemCategoryId = id;
    return dispatch(getWPCs(condition));
};


//重置查询条件

export const RESET_QUERY_PANEL = 'RESET_QUERY_PANEL';
export const resetQueryPanel = () => ({
    type: RESET_QUERY_PANEL,
});
export const SAVE_QUERY_CONDITION = 'SAVE_QUERY_CONDITION';
export const saveQueryCondition = (name, value) => ({
    type: SAVE_QUERY_CONDITION,
    name,
    value
});
/*==============================导出================================= */
export const exportHighData = () => (dispatch, getState) => {
    const {pageIndex, pageSize, productCategoryCode, productCategoryName, ...props} = getState()
        .getIn(['page', 'appState', 'queryHighCondition'])
        .toJS() || {};
    return api.exportWPC(props);
};
/*==============================新增维修项目分类================================ */

export const ADD_CATEGORY = 'ADD_CATEGORY';
export const onClickAddCategory = data => (dispatch, getState) => api.addCategory(data).then(res => {
    if(res.ok) {
        const {parentId, typeId, ...props} = data;
        const trees = getState().getIn(['page', 'domainData', 'categories', 'data']).toJS();
        const types = getState().getIn(['page', 'domainData', 'initData', 'workItemCategoryTypes']).toJS();
        const path = getPathById(trees, parentId) || [];
        const {isLeaf, name} = types.find(item => item.id === typeId) || {};
        dispatch({
            type: ADD_CATEGORY,
            path,
            data: {
                ...props,
                ...res.data,
                isLeaf,
                typeName: name,
                typeId,
                status: workItemCategoryStatus.生效,
                items: [],
                isNew: true
            }
        });
    }
    return res.ok;
});

/*==============================编辑维修项目分类================================ */
export const UPDATE_CATEGORY = 'UPDATE_CATEGORY';
export const updateCategory = (id, data) => (dispatch, getState) => {
    const trees = getState().getIn(['page', 'domainData', 'categories', 'data']).toJS();
    const path = getPathById(trees, id) || [];
    dispatch({
        type: UPDATE_CATEGORY,
        path,
        data
    });
};

export const onClickUpdateCategory = (data, id) => dispatch => {
    const {code, name, remark, rowVersion} = data;
    return api.updateCategory(id, {
        code,
        name,
        remark,
        rowVersion
    }).then(res => {
        if(res.ok)
            dispatch(updateCategory(id, {
                code,
                name,
                remark,
                ...res.data
            }));
        return res.ok;
    });
};

export const onSubmitCategory = (data, id) => dispatch => {
    if(id)
        return dispatch(onClickUpdateCategory(data, id));
    return dispatch(onClickAddCategory(data));
};
/*==============================停用维修项目分类================================ */
export const onClickDisableCategory = id => (dispatch, getState) => {
    const trees = getState().getIn(['page', 'domainData', 'categories', 'data']).toJS();
    const {status, rowVersion} = getObjById(trees, id) || {};
    return api.disableCategory(id, {rowVersion}).then(res => {
        if(res.ok)
            dispatch(updateCategory(id, {
                ...res.data,
                status: status === workItemCategoryStatus.生效 ? workItemCategoryStatus.停用 : workItemCategoryStatus.生效,
            }));
        
        return res.ok;
    });
};

/*==============================启用维修项目分类================================ */
export const onClickEnableCategory = id => (dispatch, getState) => {
    const trees = getState().getIn(['page', 'domainData', 'categories', 'data']).toJS();
    const {status, rowVersion} = getObjById(trees, id) || {};
    return api.enableCategory(id, {rowVersion}).then(res => {
        if(res.ok)
            dispatch(updateCategory(id, {
                ...res.data,
                status: status === workItemCategoryStatus.生效 ? workItemCategoryStatus.停用 : workItemCategoryStatus.生效
            }));
        
        return res.ok;
    });
};

/*==============================新增维修项目================================ */
export const onClickAddWorkItem = (workItemCategoryId, data) => (dispatch, getState) => api.addWorkItem({
    workItemCategoryId,
    workItems: data.map(item => ({
        code: item.code,
        name: item.name,
        englishName: item.englishName,
        englishRemark: item.englishRemark,
        laborHour: item.laborHour,
        productCategoryId: item.productCategoryId,
        remark: item.remark,
        isCustomed: item.isCustomed
    }))
}).then(res => res.ok);
/*==============================编辑维修项目================================ */
export const onClickUpdateWorkItem = data => (dispatch, getState) => {
    const {id, name, remark, rowVersion, englishName, laborHour, englishRemark} = data;
    return api.updateWorkItem(id, {
        name,
        remark,
        rowVersion,
        englishName,
        englishRemark,
        laborHour,
    }).then(res => res.ok);
};

/*==============================更新维修项目对应的辅助维修项目================================ */
export const onClickUpdateAssist = (id, data) => dispatch => api.updateAssist(id, data).then(res => res.ok);
/*==============================更新维修项目对应的辅助维修项目================================ */
export const onClickUpdateLaborhour = (id, data) => dispatch => api.updateLaborhour(id, data).then(res => res.ok);
/*==============================停用维修项目================================ */
export const onClickDisableWorkItem = id => (dispatch, getState) => {
    const data = getState()
        .getIn(['page', 'domainData', 'workItems', 'data'])
        .toJS();
    const {rowVersion} = data.find(item => item.id === id);
    return api.disableWorkItem(id, {
        rowVersion
    }).then(res => res.ok);
};

export const onClickDisableForDetail = id => (dispatch, getState) => {
    const {rowVersion} = getState()
        .getIn(['page', 'domainData', 'detail', 'data'])
        .toJS();
    return api.disableWorkItem(id, {
        rowVersion
    }).then(res => res.ok);
};
/*==============================启用维修项目================================ */
export const onClickEnableWorkItem = id => (dispatch, getState) => {
    const data = getState()
        .getIn(['page', 'domainData', 'workItems', 'data'])
        .toJS();
    const {rowVersion} = data.find(item => item.id === id);
    return api.enableWorkItem(id, {
        rowVersion
    }).then(res => res.ok);
};

export const onClickEnableForDetail = id => (dispatch, getState) => {
    const {rowVersion} = getState()
        .getIn(['page', 'domainData', 'detail', 'data'])
        .toJS();
    return api.enableWorkItem(id, {
        rowVersion
    }).then(res => res.ok);
};
/*==============================查询action================================= */
//修改查询条件

export const SAVE_HIGH_QUERY_CONDITION = 'SAVE_HIGH_QUERY_CONDITION';
export const saveHighQueryCondition = (name, value) => ({
    type: SAVE_HIGH_QUERY_CONDITION,
    name,
    value
});
//重置查询条件

export const RESET_HIGH_QUERY_PANEL = 'RESET_QUERY_PANEL';
export const resetHighQueryPanel = () => ({
    type: RESET_HIGH_QUERY_PANEL,
});


export const SAVE_SUBMIT_CONDITION = 'SAVE_SUBMIT_CONDITION';
export const saveSubmitCondition = (name, value) => ({
    type: SAVE_SUBMIT_CONDITION,
    name,
    value
});
/* =======================获取详情================================== */
export const GET_DETAIL_BEGIN = 'GET_DETAIL_BEGIN';
export const GET_DETAIL_SUCCESS = 'GET_DETAIL_SUCCESS';
export const GET_DETAIL_FAIL = 'GET_DETAIL_FAIL';
export const getDetailBegin = () => ({
    type: GET_DETAIL_BEGIN
});
export const getDetailSuccess = data => ({
    type: GET_DETAIL_SUCCESS,
    data
});
export const getDetailFail = () => ({
    type: GET_DETAIL_FAIL,
});

export const getDetail = id => dispatch => {
    dispatch(getDetailBegin());
    return api.getWorkItemDetail(id).then(res => {
        if(res.ok)
            dispatch(getDetailSuccess(res.data));
        else
            dispatch(getDetailFail());
        return res;
    });
};


export const SELECT_PC_QUERY = 'SELECT_PC_QUERY';
export const selectPC = data => ({
    type: SELECT_PC_QUERY,
    data: {
        productCategoryId: data.id,
        productCategoryCode: data.code,
        productCategoryName: data.name,
    }
});

//是否隐藏树
export const SELECT_SHOWTREE_OPEN = 'SELECT_SHOWTREE_OPEN';
export const showTreeOpen = () => ({
    type: SELECT_SHOWTREE_OPEN
});
export const SELECT_SHOWTREE_CLOSE = 'SELECT_SHOWTREE_CLOSE';
export const showTreeClose = () => ({
    type: SELECT_SHOWTREE_CLOSE
});

